import 'dart:async';

import 'package:casdon/modules/lifeCircle/data/model/life_banner_module.dart';
import 'package:casdon/modules/lifeCircle/domain/states/life_banner_list_state.dart';
import 'package:casdon/modules/lifeCircle/providers/life_provider.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class LifeBannerListNotifier extends AsyncNotifier<LifeBannerListState> {
  static LifeBannerListState? _cachedState;

  @override
  Future<LifeBannerListState> build() async {
    if (_cachedState != null) {
      Future.microtask(_refreshSilently);
      return _cachedState!;
    }
    final data = await _fetchData();
    _cachedState = data;
    return data;
  }

  Future<void> refresh() async {
    await _refreshSilently();
  }

  Future<void> _refreshSilently() async {
    try {
      final newState = await _fetchData();
      _cachedState = newState;

      state = AsyncValue.data(newState);
    } catch (e, st) {
      if (_cachedState == null) {
        state = AsyncValue.error(e, st);
      }
    }
  }

  Future<LifeBannerListState> _fetchData() async {
    final ret = await ref.read(lifeBannerListUsecaseProvider).execute();
    final data = LifeBannerModule.listFromApi(ret);
    data.sort((a, b) => a.sort.compareTo(b.sort));
    return LifeBannerListState(data: data);
  }
}
